<?php
class SJDB {
	private $autoThrowException = true;
	private $pearDbObj;
	static private $instance;
	public function setAutoThrowException($value) {
		$this->autoThrowException = $value;
	}
	private function dbErrorHandle($res) {
		if (PEAR::isError($res) && $this->autoThrowException) {
			$userInfo = $res->getUserInfo();
			if (preg_match('/nativecode=(\d+)/', $userInfo, $matches) && count($matches) == 2) {
				$nativeCode = intval($matches[1]);
				switch ($nativeCode) {
					case 1216:
					case 1452:
						throw new DBException('添加或修改外键子记录错误:没有相应父记录');
					case 1217:
					case 1451:
						throw new DBException('删除或修改外键父记录出错:有相关子记录存在');
					case 1064:
						throw new DBException('SQL语法错误');
				}
			}
			throw new DBException('数据库查询出错');
		} else {
			return $res;
		}
	}
	static public function getInstance() {
		if (!(self::$instance instanceof self)) {
			self::$instance = new self(MYSQLDSN);
		}
		return self::$instance;
	}
	public function __construct($DSN) {
		$this->pearDbObj = DB::connect($DSN);
		if (PEAR::isError($this->pearDbObj)) {
			die(json_encode(array('success' => false, 'msg' => '无法连接到数据库！')));
		}
	}
	public function __call($funcName, $args) {
		$rc = new ReflectionClass($this->pearDbObj);
		if ($rc->hasMethod($funcName)) {
			$method = $rc->getMethod($funcName);
			return $this->dbErrorHandle($method->invokeArgs($this->pearDbObj, $args));
		}
	}
}
?>